import {defineStore} from 'pinia'
import {socketService} from '@/services/socketService'
import router from '@/router'
import { ref, computed, onUnmounted } from 'vue'
import { useGameStore } from '@/stores/game'
import { usePlayerStore } from '@/stores/player'

export const useRoomStore = defineStore('room',{
    state:() =>({
        roomId:null,
        players:[],
        gameStatus:'waiting', // waiting, ready, starting, playing, finished
        startCountdown: 0,
        selectedColors: [],
        countdownTimer: null,
        tempPlayerId: null, // 用于临时存储joinRoom返回的playerId，等待GameUpdated事件
        currentPlayerId: null // 用于持久化存储当前玩家ID
    }),
    
    getters: {
        // 检查颜色是否已被其他玩家选择
        isColorSelected: (state) => (color) => {
            return state.players.some(player => player.color === color && player.id !== state.players.find(p => p.isCurrent)?.id);
        },
        
        // 获取已准备的玩家数量
        readyPlayersCount: (state) => {
            return state.players.filter(player => player.ready).length;
        },
        
        // 检查游戏是否可以开始
        canStartGame: (state) => {
            // 游戏可以开始的条件：至少有2名玩家，所有玩家都准备好，游戏状态为ready、waiting或starting
            return state.players.length >= 2 && state.readyPlayersCount === state.players.length && (state.gameStatus === 'ready' || state.gameStatus === 'waiting' || state.gameStatus === 'starting');
        }
    },
    actions:{
        // 清除游戏列表缓存
        clearGameList() {
            console.log('执行清除游戏列表缓存操作')
            socketService.clearGamesCache()
        },
        
        async createRoom(name, customId = null) {
            try {
                // 创建房间前先清除游戏列表缓存，确保获取最新数据
                this.clearGameList()
                
                const room = await socketService.createRoom(name, customId)
                this.roomId = room.room.id
                
                // 优化：不立即添加本地玩家，而是等待GameUpdated事件来正确更新和标记玩家
                // 生成临时playerId用于在GameUpdated事件中标记当前玩家
                const tempPlayerId = crypto.randomUUID()
                console.log('创建房间，已保存临时playerId:', tempPlayerId)
                this.tempPlayerId = tempPlayerId
                
                // 使用路由跳转
                router.push({ path: '/game', query: { roomId: this.roomId } })
            } catch (error) {
                console.error('创建房间失败:', error)
                // 不使用模拟数据，让错误正常显示给用户
                throw error
            }
        },
        
        async joinRoom(id) {
            console.log('===== roomStore.joinRoom 被调用 =====')
            console.log('请求加入的房间ID:', id)
            
            // 加入房间前先清除游戏列表缓存，确保获取最新数据
            this.clearGameList()
            
            try {
                console.log('调用socketService.joinRoom')
                const result = await socketService.joinRoom(id)
                console.log('socketService.joinRoom 成功返回，结果:', result)
                
                this.roomId = id
                console.log('已设置roomId:', id)
                
                // 保存临时playerId
                if (result && result.playerId) {
                    console.log('保存临时playerId:', result.playerId)
                    this.tempPlayerId = result.playerId
                } else {
                    console.log('未获取到playerId或result为空')
                }
                
                // 立即刷新玩家列表并标记当前玩家，不再只依赖GameUpdated事件
                console.log('立即刷新玩家列表并标记当前玩家')
                await this.refreshPlayerListAndUpdateUI()
                
                // 使用路由跳转
                router.push({ path: '/game', query: { roomId: this.roomId } })
                console.log('已执行路由跳转至游戏页面')
            } catch (error) {
                console.error('加入房间失败:', error)
                throw error
            }
        },
        
        // 添加当前玩家
        addCurrentPlayer(name, playerId = null) {
            // 清除旧的当前玩家
            this.players = this.players.filter(p => !p.isCurrent)
            // 添加新的当前玩家，使用真实的playerId或生成唯一ID
            this.players.push({
                id: playerId || crypto.randomUUID(),
                name: name,
                color: '#000',
                score: 0,
                area: 0,
                ready: false,
                isCurrent: true
            })
        },
        async leaveRoom() {
            if (this.roomId) {
                // 找到当前玩家ID
                const currentPlayer = this.players.find(p => p.isCurrent)
                const playerId = currentPlayer ? currentPlayer.id : null
                
                // 尝试通知服务器离开房间
                try {
                    await socketService.leaveRoom(this.roomId, playerId)
                } catch (error) {
                    // 如果服务器连接不上，也继续执行本地状态重置
                    console.log('离开房间时出错，可能是服务器未连接')
                }
                
                // 清除游戏列表缓存
                socketService.clearGamesCache()
                
                // 重置本地状态
                this.roomId = null
                this.players = []
                this.gameStatus = 'waiting'
            }
        },
        // 统一setPlayer和setPlayers方法的行为
        setPlayer(list) {
            this.setPlayers(list)
        },
        
        setPlayers(list) {
            console.log('===== 开始更新玩家列表 =====');
            console.log('原始玩家列表数据:', list)
            console.log('房间ID:', this.roomId);
            
            // 保存当前玩家ID和现有玩家的area属性
            const currentPlayerId = this.players.find(p => p.isCurrent)?.id;
            const existingAreas = new Map();
            this.players.forEach(player => {
                if (player.id && player.area !== undefined) {
                    existingAreas.set(player.id, player.area);
                }
            });
            console.log('保存的当前玩家ID:', currentPlayerId);
            console.log('保存的玩家面积数据:', Object.fromEntries(existingAreas));
            
            // 确保list是数组
            const playersList = Array.isArray(list) ? list : [];
            console.log('处理后玩家数量:', playersList.length);
            
            // 打印每个玩家的详细信息
            if (playersList.length > 0) {
                console.log('玩家详细信息:');
                playersList.forEach((player, index) => {
                    console.log(`玩家${index + 1}:`, {
                        id: player.id,
                        name: player.name,
                        ready: player.ready,
                        color: player.color,
                        score: player.score,
                        area: existingAreas.get(player.id) || 0
                    });
                });
            }
            
            // 更新玩家列表，保留area属性
            this.players = playersList.map(player => ({
                ...player,
                area: existingAreas.get(player.id) || 0
            }));
            
            // 清除所有玩家的isCurrent标记
            this.players.forEach(p => p.isCurrent = false);
            console.log('已清除所有玩家的isCurrent标记');
            
            // 优先使用tempPlayerId标记当前玩家
            if (this.tempPlayerId) {
                console.log('尝试使用tempPlayerId标记当前玩家:', this.tempPlayerId);
                
                // 增强的匹配逻辑，尝试多种匹配方式
                let tempPlayer = null;
                let matchType = null;
                
                // 1. 精确匹配
                tempPlayer = this.players.find(p => p.id === this.tempPlayerId);
                if (tempPlayer) {
                    matchType = '精确匹配';
                }
                
                // 2. 如果精确匹配失败，尝试双向部分包含匹配
                if (!tempPlayer) {
                    tempPlayer = this.players.find(p => p.id.includes(this.tempPlayerId) || this.tempPlayerId.includes(p.id));
                    if (tempPlayer) {
                        matchType = '双向部分包含匹配';
                    }
                }
                
                // 3. 如果都失败，尝试检查玩家名称中是否包含临时ID的一部分
                if (!tempPlayer) {
                    const tempIdPart = this.tempPlayerId.substring(0, 8); // 取临时ID的前8个字符
                    tempPlayer = this.players.find(p => p.id.includes(tempIdPart) || p.name.includes(tempIdPart));
                    if (tempPlayer) {
                        matchType = '部分ID匹配';
                    }
                }
                
                // 4. 如果都失败，检查是否是房间创建者（名称中包含"Creator"）
                if (!tempPlayer) {
                    tempPlayer = this.players.find(p => p.name && p.name.includes('Creator'));
                    if (tempPlayer) {
                        matchType = '创建者匹配';
                    }
                }
                
                // 5. 如果都失败，检查玩家数量，如果只有一个玩家，则标记为当前玩家
                if (!tempPlayer && this.players.length === 1) {
                    tempPlayer = this.players[0];
                    matchType = '单玩家默认匹配';
                }
                
                // 6. 如果都失败，尝试将最新加入的玩家（最后一个）标记为当前玩家
                if (!tempPlayer && this.players.length > 0) {
                    tempPlayer = this.players[this.players.length - 1];
                    matchType = '最新玩家匹配';
                }
                
                if (tempPlayer) {
                    tempPlayer.isCurrent = true;
                    console.log(`已使用${matchType}标记当前玩家:`, tempPlayer.name, 'ID:', tempPlayer.id);
                    // 标记完成后清除tempPlayerId
                    this.tempPlayerId = null;
                    console.log('已清除tempPlayerId');
                } else {
                    console.log('未找到与tempPlayerId匹配的玩家，当前玩家列表中的ID:', this.players.map(p => p.id));
                    console.log('tempPlayerId:', this.tempPlayerId);
                    
                    // 移除创建本地玩家的逻辑，因为这会导致玩家列表不一致
                    console.warn('警告：tempPlayerId未匹配到任何玩家，将尝试其他方式标记当前玩家');
                    
                    // 无论是否找到匹配的玩家，都清除tempPlayerId
                    this.tempPlayerId = null;
                    console.log('已清除tempPlayerId');
                }
            } else {
                console.log('tempPlayerId不存在，跳过tempPlayerId标记');
            }
            
            // 如果没有tempPlayerId或找不到对应玩家，尝试使用之前的currentPlayerId
            if (currentPlayerId && !this.players.some(p => p.isCurrent)) {
                console.log('尝试使用现有currentPlayerId标记当前玩家:', currentPlayerId);
                const existingPlayer = this.players.find(p => p.id === currentPlayerId || p.id.includes(currentPlayerId));
                if (existingPlayer) {
                    existingPlayer.isCurrent = true;
                    console.log('已使用现有currentPlayerId标记当前玩家:', existingPlayer.name);
                    return;
                } else {
                    console.log('未找到与currentPlayerId匹配的玩家');
                }
            }
            
            // 如果都找不到且没有当前玩家，将第一个玩家标记为当前玩家
            if (this.players.length > 0 && !this.players.some(p => p.isCurrent)) {
                this.players[0].isCurrent = true;
                console.log('已将第一个玩家标记为当前玩家:', this.players[0].name);
            }
            
            // 打印最终玩家列表状态，用于调试
            console.log('更新后的玩家列表状态:', this.players.map(p => ({name: p.name, id: p.id, isCurrent: p.isCurrent})));
        },
        
        setStatus(status) {
            this.gameStatus = status
        },
        
        async setPlayerReady(ready) {
            const currentPlayer = this.players.find(p => p.isCurrent)
            if (currentPlayer) {
                // 保存当前状态快照
                const stateSnapshot = {
                    color: currentPlayer.color,
                    ready: currentPlayer.ready
                }
                
                try {
                    currentPlayer.ready = ready
                    
                    // 同步到gameStore
                    const gameStore = useGameStore()
                    gameStore.myColor = stateSnapshot.color
                    
                    if (this.roomId) {
                        await socketService.setPlayerReady(this.roomId, currentPlayer.id, ready)
                        
                        // 双重检查颜色
                        if (currentPlayer.color !== stateSnapshot.color) {
                            console.warn('颜色被意外修改，正在恢复...')
                            currentPlayer.color = stateSnapshot.color
                        }

                        // 玩家准备状态变化后，检查是否可以开始游戏
                        this.checkAndStartGameCountdown()
                    }
                } catch (error) {
                    // 出错时恢复状态
                    currentPlayer.ready = stateSnapshot.ready
                    currentPlayer.color = stateSnapshot.color
                    throw error
                }
            }
        },
        
        // 设置玩家颜色
        async setPlayerColor(color) {
            const currentPlayer = this.players.find(p => p.isCurrent)
            if (currentPlayer) {
                // 检查颜色是否已被其他玩家选择
                if (this.isColorSelected(color)) {
                    console.warn(`无法设置颜色 ${color}，此颜色已被其他玩家选择`)
                    return false
                }
                
                // 无论游戏状态如何，都允许设置颜色
                currentPlayer.color = color
                console.log(`设置当前玩家颜色: ${color}`)
                
                // 同步到gameStore
                const gameStore = useGameStore()
                gameStore.myColor = color
                
                // 同步到playerStore
                const playerStore = usePlayerStore()
                playerStore.setColor(color)
                
                // 通知服务器更新玩家颜色
                try {
                    if (this.roomId) {
                        await socketService.setPlayerColor(this.roomId, currentPlayer.id, color)
                        console.log('已通知服务器玩家颜色:', color)
                    }
                } catch (error) {
                    console.error('通知服务器颜色失败:', error)
                    // 即使发送失败，也返回true，因为前端设置成功了
                }
                
                return true
            }
            console.warn(`无法设置颜色 ${color}，未找到当前玩家`)
            return false
        },
        
        // 调试方法：强制设置当前玩家
    forceSetCurrentPlayer() {
        console.log('===== 强制设置当前玩家 =====')
        console.log('当前玩家列表:', this.players.map(p => ({name: p.name, id: p.id, isCurrent: p.isCurrent})))
        
        // 清除所有玩家的isCurrent标记
        this.players.forEach(p => p.isCurrent = false)
        console.log('已清除所有玩家的isCurrent标记')
        
        // 优先使用tempPlayerId标记当前玩家
        if (this.tempPlayerId) {
            console.log('尝试使用tempPlayerId标记当前玩家:', this.tempPlayerId)
            
            // 增强的匹配逻辑，尝试多种匹配方式
            let tempPlayer = null
            let matchType = null
            
            // 1. 精确匹配
            tempPlayer = this.players.find(p => p.id === this.tempPlayerId)
            if (tempPlayer) {
                matchType = '精确匹配'
            }
            
            // 2. 如果精确匹配失败，尝试双向部分包含匹配
            if (!tempPlayer) {
                tempPlayer = this.players.find(p => p.id.includes(this.tempPlayerId) || this.tempPlayerId.includes(p.id))
                if (tempPlayer) {
                    matchType = '双向部分包含匹配'
                }
            }
            
            // 3. 如果都失败，尝试检查玩家ID中是否包含临时ID的一部分
            if (!tempPlayer) {
                const tempIdPart = this.tempPlayerId.substring(0, 8) // 取临时ID的前8个字符
                tempPlayer = this.players.find(p => p.id.includes(tempIdPart))
                if (tempPlayer) {
                    matchType = '部分ID匹配'
                }
            }
            
            if (tempPlayer) {
                tempPlayer.isCurrent = true
                console.log(`已使用${matchType}标记当前玩家:`, tempPlayer.name, 'ID:', tempPlayer.id)
            } else {
                console.log('未找到与tempPlayerId匹配的玩家，当前玩家列表中的ID:', this.players.map(p => p.id))
            }
        } else {
            console.log('tempPlayerId不存在，跳过tempPlayerId标记')
        }
        
        // 如果没有使用tempPlayerId找到玩家，尝试使用之前的currentPlayerId
        const currentPlayerId = this.players.find(p => p.isCurrent)?.id || null
        if (!this.players.some(p => p.isCurrent)) {
            const storedCurrentPlayerId = this.currentPlayerId || null
            if (storedCurrentPlayerId) {
                console.log('尝试使用现有currentPlayerId标记当前玩家:', storedCurrentPlayerId)
                const existingPlayer = this.players.find(p => p.id === storedCurrentPlayerId || p.id.includes(storedCurrentPlayerId))
                if (existingPlayer) {
                    existingPlayer.isCurrent = true
                    console.log('已使用现有currentPlayerId标记当前玩家:', existingPlayer.name)
                } else {
                    console.log('未找到与currentPlayerId匹配的玩家')
                }
            }
        }
        
        // 如果仍然没有找到当前玩家，并且有玩家列表不为空
        if (this.players.length > 0 && !this.players.some(p => p.isCurrent)) {
            console.log('未找到匹配的玩家，将尝试将最新加入的玩家标记为当前玩家')
            // 尝试将最后一个玩家（假设是最新加入的）标记为当前玩家
            const latestPlayer = this.players[this.players.length - 1]
            latestPlayer.isCurrent = true
            console.log('已将最新加入的玩家标记为当前玩家:', latestPlayer.name)
        }
        
        console.log('更新后的玩家列表:', this.players.map(p => ({name: p.name, id: p.id, isCurrent: p.isCurrent})))
        
        // 保存当前玩家ID
        const currentPlayer = this.players.find(p => p.isCurrent)
        if (currentPlayer) {
            this.currentPlayerId = currentPlayer.id
            console.log('已保存当前玩家ID:', this.currentPlayerId)
        }
    },
    
    // 刷新玩家列表并强制更新UI
    async refreshPlayerListAndUpdateUI() {
        console.log('===== 刷新玩家列表并强制更新UI =====')
        
        // 首先，强制设置当前玩家
        this.forceSetCurrentPlayer()
        
        // 然后，尝试主动获取游戏更新（禁用缓存确保获取最新数据）
        try {
            console.log('主动请求游戏更新以获取完整玩家列表（禁用缓存）')
            const games = await socketService.getActiveGames(false)
            console.log('获取到的最新游戏列表，数量:', games?.length || 0)
            
            // 检查是否找到了当前房间
            if (games && Array.isArray(games)) {
                const currentGame = games.find(game => game.id === this.roomId)
                if (currentGame) {
                    console.log('找到了当前房间:', currentGame.name)
                    console.log('房间中的玩家数量:', currentGame.players?.length || 0)
                }
            }
        } catch (error) {
            console.error('主动请求游戏更新失败:', error)
        }
        
        // 强制触发UI更新
        console.log('强制触发UI更新')
        this.tempUpdateTrigger = Date.now() // 利用响应式系统强制更新UI
        
        // 短暂延迟后再次检查玩家状态
        setTimeout(() => {
            const currentPlayer = this.players.find(p => p.isCurrent)
            console.log('刷新后当前玩家:', currentPlayer ? `${currentPlayer.name} (ID: ${currentPlayer.id})` : '未设置')
        }, 100)
    },
    
    // 检查并开始游戏倒计时
    checkAndStartGameCountdown() {
        if (this.canStartGame && this.gameStatus !== 'starting') {
            this.gameStatus = 'starting'
            this.startCountdown = 6
                
                // 清除旧的计时器
                if (this.countdownTimer) {
                    clearInterval(this.countdownTimer)
                }
                
                // 设置新的倒计时器
                this.countdownTimer = setInterval(() => {
                    this.startCountdown--
                    
                    if (this.startCountdown <= 0) {
                        this.startGame()
                    }
                }, 1000)
            }
        },
        
        // 开始游戏
        async startGame() {
            if (this.countdownTimer) {
                clearInterval(this.countdownTimer)
                this.countdownTimer = null
            }

            // 再次检查是否满足开始游戏的条件
            if (!this.canStartGame) {
                console.warn('不满足开始游戏的条件，玩家数量不足2人或有玩家未准备好')
                this.gameStatus = 'ready'
                return
            }

            // 找到当前玩家ID
            const currentPlayer = this.players.find(p => p.isCurrent)
            const playerId = currentPlayer ? currentPlayer.id : null

            // 通知服务器开始游戏
            if (this.roomId && playerId) {
                try {
                    await socketService.startGame(this.roomId, playerId)
                    // 服务器成功响应后才设置游戏状态为playing
                    this.gameStatus = 'playing'
                    this.startCountdown = 0
                    
                    // 启动游戏倒计时
                    const gameStore = useGameStore()
                    gameStore.startGameTimer()
                } catch (error) {
                    console.error('开始游戏时通知服务器失败:', error)
                    // 增强的错误处理：根据错误类型提供更明确的反馈
                    if (error.message && error.message.includes('后端玩家数量不足')) {
                        console.warn('后端报告玩家数量不足，将刷新玩家列表并更新UI')
                        // 为了避免async/await嵌套问题，使用Promise方式处理
                        this.refreshPlayerListAndUpdateUI().catch(err => {
                            console.error('刷新玩家列表失败:', err)
                        })
                    }
                    // 处理服务器意外错误
                    else if (error.message && (error.message.includes('unexpected error') || error.message.includes('服务器返回错误'))) {
                        console.log('检测到服务器意外错误，尝试直接使用备用方法')
                        try {
                            // 尝试使用备用方法
                            const directResult = await socketService.startGameDirect(this.roomId, playerId)
                            if (directResult) {
                                console.log('备用方法调用成功')
                                this.gameStatus = 'playing'
                                this.startCountdown = 0
                                
                                // 启动游戏倒计时
                                const gameStore = useGameStore()
                                gameStore.startGameTimer()
                                return
                            }
                        } catch (directError) {
                            console.error('备用方法也调用失败:', directError)
                        }
                    }
                    // 如果失败，重置游戏状态
                    this.gameStatus = 'ready'
                }
            } else {
                console.error('无法开始游戏：房间ID或玩家ID不存在')
                this.gameStatus = 'ready'
            }
        },
        
        // 结束游戏
        endGame() {
            this.gameStatus = 'finished'
            
            // 停止任何可能的计时器
            if (this.countdownTimer) {
                clearInterval(this.countdownTimer)
                this.countdownTimer = null
            }
            
            // 通知所有玩家游戏结束
            // 这里可以添加游戏结束后的其他逻辑，如显示排名等
            console.log('游戏结束！')
        },
        
        // 设置当前房间
        setCurrentRoom(room) {
            this.roomId = room.id
            // 这里可以根据需要初始化其他与房间相关的状态
            console.log('设置当前房间:', this.roomId)
        }
    },
    
    // 销毁时清除计时器
    unmounted() {
        if (this.countdownTimer) {
            clearInterval(this.countdownTimer)
        }
    }
})